//
//  QTMutableDictionary.m
//  Pods
//
//  Created by 张俊博 on 16/8/25.
//
//

#import "QTMutableDictionary.h"

@implementation QTMutableDictionary

- (void)dealloc
{
    pthread_mutex_destroy(&_mutex);
}

- (instancetype)init
{
    if (self = [super init])
    {
        pthread_mutex_init(&_mutex, NULL);
        _safeDictionary = [NSMutableDictionary dictionary];
//        _lock = OS_SPINLOCK_INIT;
//        _signal = dispatch_semaphore_create(1);
    }
    return self;
}

- (void)lock
{
    pthread_mutex_lock(&_mutex);
//    OSSpinLockLock(&_lock);
//    dispatch_semaphore_wait(_signal, DISPATCH_TIME_FOREVER);
}

- (void)unlock
{
    pthread_mutex_unlock(&_mutex);
//    OSSpinLockUnlock(&_lock);
//    dispatch_semaphore_signal(_signal);
}

- (id)objectForKey:(id)aKey
{
    if (!aKey) return nil;
    return [_safeDictionary objectForKey:aKey];
}

- (NSArray *)allKeys
{
    return [_safeDictionary allKeys];
}

- (NSArray *)allKeysForObject:(id)anObject
{
    return [_safeDictionary allKeysForObject:anObject];
}

- (NSArray *)allValues
{
    [self lock];
    NSArray *array = [_safeDictionary allValues];
    [self unlock];
    return array;
}

- (void)removeObjectForKey:(id)aKey
{
    if (!aKey) return;
    
    [self lock];
    [_safeDictionary removeObjectForKey:aKey];
    [self unlock];
}

- (void)setObject:(id)anObject forKey:(id)aKey
{
    if (!anObject || !aKey) return;
    
    [self lock];
    [_safeDictionary setObject:anObject forKey:aKey];
    [self unlock];
}

- (void)removeAllObjects
{
    [self lock];
    [_safeDictionary removeAllObjects];
    [self unlock];
}

- (void)removeObjectsForKeys:(NSArray *)keyArray
{
    [self lock];
    [_safeDictionary removeObjectsForKeys:keyArray];
    [self unlock];
}

- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary
{
    [self lock];
    [_safeDictionary addEntriesFromDictionary:otherDictionary];
    [self unlock];
}

- (void)setDictionary:(NSDictionary *)otherDictionary
{
    [self lock];
    [_safeDictionary setDictionary:otherDictionary];
    [self unlock];
}

- (NSMutableDictionary *)safeDictionaryCopy
{
    NSMutableDictionary *temp;
    [self lock];
    temp = self.safeDictionary.mutableCopy;
    [self unlock];
    return temp;
}

- (NSUInteger)count
{
    return _safeDictionary.count;
}

@end
